package com.example.common.utils;

import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import java.io.*;
import java.util.Base64;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hwpf.HWPFDocumentCore;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.converter.WordToHtmlUtils;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;



public class FileTOHtml {

    public static String getFIleType(String fileName){
        String fileExt =fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        if(("doc").equals(fileExt) || ("docx").equals(fileExt)){
            return "word";
        }else if(("xls").equals(fileExt) || ("xlsx").equals(fileExt)){
            return "excel";
        }else if(("ppt").equals(fileExt) || ("pptx").equals(fileExt)){
            return "ppt";
        }else{
            return "other";
        }
    }

    public static String Word2007ToHtml(String filePath,String realPath) throws IOException {
        String newFileName ="word2007"+ String.valueOf(new Date())+".html";
        String newPath = realPath+ "/"+newFileName;
        File f = new File(filePath);
        if (!f.exists()) {
            System.out.println("Sorry File does not Exists!");
        } else {
            if (f.getName().endsWith(".docx") || f.getName().endsWith(".DOCX")) {

                // 1) 加载XWPFDocument及文件
                InputStream in = new FileInputStream(f);
                XWPFDocument document = new XWPFDocument(in);

                // 2) 实例化XHTML内容(这里将会把图片等文件放到生成的"word/media"目录)
//                File imageFolderFile = new File(realPath);
////                XHTMLOptions options = XHTMLOptions.create().URIResolver(
////                        new FileURIResolver(imageFolderFile));
////                options.setExtractor(new FileImageExtractor(imageFolderFile));
////
////                // 3) 将XWPFDocument转成XHTML并生成文件
////                OutputStream out = new FileOutputStream(new File(
////                        newPath));
////                XHTMLConverter.getInstance().convert(document, out, null);
                //
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                XHTMLConverter.getInstance().convert(document, outputStream, null);
                String value = new String(outputStream.toByteArray());
                FileUtils.writeStringToFile(new File(realPath, newFileName), value, "UTF-8");
            } else {
                System.out.println("Enter only MS Office 2007+ files");
            }
        }
        return "/materials/real_file/"+newFileName;
    }

    public static String Word2003ToHtml(String filePath,String realPath) throws IOException, ParserConfigurationException, TransformerException {
        HWPFDocumentCore wordDocument = WordToHtmlUtils.loadDoc(new FileInputStream(filePath));
        WordToHtmlConverter wordToHtmlConverter = new ImageConverter(
                DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()
        );
        wordToHtmlConverter.processDocument(wordDocument);
        Document htmlDocument = wordToHtmlConverter.getDocument();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(out);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer serializer = transformerFactory.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        serializer.transform(domSource, streamResult);
        out.close();
        String result = new String(out.toByteArray());
        String newFileName ="word2003"+ String.valueOf(new Date())+".html";
//        String newPath = realPath+ "/"+newFileName;
        FileUtils.writeStringToFile(new File(realPath, newFileName), result, "GBK");
        return "/materials/real_file/"+newFileName;
    }

    public static class ImageConverter extends WordToHtmlConverter{

        public ImageConverter(Document document) {
            super(document);
        }
        @Override
        protected void processImageWithoutPicturesManager(Element currentBlock, boolean inlined, Picture picture){
            Element imgNode = currentBlock.getOwnerDocument().createElement("img");
            StringBuffer sb = new StringBuffer();
            sb.append(Base64.getMimeEncoder().encodeToString(picture.getRawContent()));
            sb.insert(0, "data:" + picture.getMimeType() + ";base64,");
            imgNode.setAttribute("src", sb.toString());
            currentBlock.appendChild(imgNode);
        }
    }
}
